<?php
/**
 * 年度用户跑步数据
 * Created by PhpStorm.
 * User: 章利桂
 * Date: 2016/12/15
 * Time: 11:48
 */
/**
 * 跑步数据分析
 */
class analysisRunWebController extends base {
    public function __construct() {
        parent::__construct('show');
        $this->in_user();
        $this->printResult = TRUE;
    }

    /**
     * cron 生成年度用户数据
     */
    public function dogetAllRunData() {
//        $uid = 4679541;
//        $created = $this->load('group')->myGroupListByRole($uid, 1);
//        $joined = $this->load('group')->myGroupListByRole($uid, 3);
//
//        var_dump($created,$joined);  exit;

        ini_set('memory_limit','2048M');
        $startTime = strtotime(date('2016-01-01'));
        $endTime = strtotime(date('2017-01-01'));
        echo date('Y-m-d H:i:s').'START'.PHP_EOL;
         $arrUid = $this->db->getAll("select DISTINCT uid from user_run_city_list");
        echo date('Y-m-d H:i:s').'CONTINUE-UID已查出，继续'.PHP_EOL;
        if(!$arrUid) return false;

        $year = date('Y',$startTime);
        foreach ($arrUid as $key=>$val) {
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.PHP_EOL;
            $reportUid = $val['uid'];
            if (!$reportUid) {
               continue;
            }
            //总里程
            $mileage = $this->db->getOne("select sum(`mileage`) as totalMileage from r_data where uid=$reportUid and overSpeed=0 and updatetime>=$startTime and updatetime<$endTime");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-2'.PHP_EOL;
            //马拉松个数 保留一位小数
            $marathonCnt = bcdiv($mileage, 42, 1);
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-3'.PHP_EOL;
            //跑过的城市个数
            $cityCnt = $this->db->getOne("select count(distinct city) from user_run_city_list where uid= $reportUid and `date`='$year' and flag=0" );
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-4'.PHP_EOL;
            //经常跑步的城市
            $arrCity = $this->db->getRow("select city,count(1) as cnt from user_run_city_list where uid= $reportUid and `date`='$year' and flag=0 GROUP BY city ORDER BY cnt desc limit 1");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-5'.PHP_EOL;
            $city = '';
            if($arrCity && isset($arrCity['city'])) {
                $city = $arrCity['city'];
            }
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-6'.PHP_EOL;
            //跑步次数
            $runCnt = $this->db->getOne("select count(1) from r_data where uid=$reportUid and overSpeed=0 and updatetime>=$startTime and updatetime<$endTime and is_delete=0");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-7'.PHP_EOL;
            //平均每周跑步次数   总跑步次数 / 跑步周数
            $weekCnt = date('W', $endTime-86400); //跑步周数
            $runAvgCnt = bcdiv($runCnt, $weekCnt, 1);
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-8'.PHP_EOL;
            //跑步时间段
            $oftenRunPeriod = 0;
            $arrAll = $sort1 = $sort2 = array();
            /*早晨*/
            $cnt1 = $this->db->getOne("select count(1) from r_data
                            where uid=$reportUid
                            and overSpeed = 0
                            and updatetime>=$startTime
                            and updatetime<$endTime
                            and updatetime > 0
                            and from_unixtime((updatetime-elapsedtime), '%H') >=3
                            and from_unixtime((updatetime-elapsedtime), '%H') <9
                    ");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-9'.PHP_EOL;
            if($cnt1>0) {
                $arrAll[] = array(1,$cnt1);
                $sort1[] = 1;
                $sort2[] = $cnt1;
            } ;
            /*上午*/
            $cnt2 = $this->db->getOne("select count(1) from r_data
                            where uid=$reportUid
                            and overSpeed = 0
                            and updatetime>=$startTime
                            and updatetime<$endTime
                            and updatetime > 0
                            and from_unixtime((updatetime-elapsedtime), '%H') >=9
                            and from_unixtime((updatetime-elapsedtime), '%H') <11
                    ");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-10'.PHP_EOL;
            if($cnt2>0) {
                $arrAll[] = array(2,$cnt2);
                $sort1[] = 2;
                $sort2[] = $cnt2;
            } ;
            /*中午*/
            $cnt3 = $this->db->getOne("select count(1) from r_data
                            where uid=$reportUid
                            and overSpeed = 0
                            and updatetime>=$startTime
                            and updatetime<$endTime
                            and updatetime > 0
                            and from_unixtime((updatetime-elapsedtime), '%H') >=11
                            and from_unixtime((updatetime-elapsedtime), '%H') <13
                    ");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-11'.PHP_EOL;

            if($cnt3>0) {
                $arrAll[] = array(3,$cnt3);
                $sort1[] = 3;
                $sort2[] = $cnt3;
            } ;
            /*下午*/
            $cnt4 = $this->db->getOne("select count(1) from r_data
                            where uid=$reportUid
                            and overSpeed = 0
                            and updatetime>=$startTime
                            and updatetime<$endTime
                            and updatetime > 0
                            and from_unixtime((updatetime-elapsedtime), '%H') >=13
                            and from_unixtime((updatetime-elapsedtime), '%H') <19
                    ");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-12'.PHP_EOL;

            if($cnt4>0) {
                $arrAll[] = array(4,$cnt4);
                $sort1[] = 4;
                $sort2[] = $cnt4;
            } ;
            /*夜晚*/
            $cnt5 = $this->db->getOne("select count(1) from r_data
                            where uid=$reportUid
                            and overSpeed = 0
                            and updatetime>=$startTime
                            and updatetime<$endTime
                            and updatetime > 0
                            and (from_unixtime((updatetime-elapsedtime), '%H') >=19
                                or from_unixtime((updatetime-elapsedtime), '%H') <3)
                    ");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-13'.PHP_EOL;

            if($cnt5>0) {
                $arrAll[] = array(5,$cnt5);
                $sort1[] = 5;
                $sort2[] = $cnt5;
            } ;
            if (count($arrAll) >0) {
                array_multisort($sort2, SORT_ASC, $sort1, SORT_ASC, $arrAll);
                $tmp = end($arrAll);
                $oftenRunPeriod = $tmp[0];
            }
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-14'.PHP_EOL;

            //跑步有道发帖
         $postsCnt = $this->db->getOne("select count(1) from r_news where uid=$reportUid and add_time>=$startTime and add_time<$endTime");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-15'.PHP_EOL;
         //被点赞数
         $byLight1 = $this->db->getOne("select count(1) from r_news_likes as a left join r_news as b on b.news_id=a.news_id where b.uid=$reportUid and a.add_time>=$startTime and a.add_time<$endTime");//帖子被点赞数
         $byLight2  = $this->db->getOne("select sum(`lights`) from  r_news_comment where uid=$reportUid and add_time>=$startTime and add_time<$endTime");//跑步有道帖子回复被点亮的次数
         $byLight3  = $this->db->getOne("select count(1) from r_uclightsrecord where uid=$reportUid and add_time>=$startTime and add_time<$endTime");//个人中心被点赞的数量
         $byLight4 =  $this->db->getOne("select count(1) from r_pm_supporters where target_uid =$reportUid and `type`=2 and `date`>=".date('Ymd',$startTime)." and `date`<".date('Ymd',$endTime));//跑么杯被点赞数
         $byLightCnt = $byLight1+$byLight2+$byLight3+$byLight4;
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-16'.PHP_EOL;

            //点赞数
          $light1  = $this->db->getOne("select count(1) from  r_news_likes where uid=$reportUid and add_time>=$startTime and add_time<$endTime");//跑步有道帖子的喜欢书
          $light2 = $this->db->getOne("select count(1) from r_uclightsrecord where light_uid = $reportUid and add_time>=$startTime and add_time<$endTime");//个人中心点赞数量
          $light3 = $this->db->getOne("select count(1) from r_pm_supporters where uid =$reportUid and `type`=2 and `date`>=".date('Ymd',$startTime)." and `date`<".date('Ymd',$endTime));//跑么杯点赞数量
          $lightCnt = $light1+$light2+$light3;
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-17'.PHP_EOL;

            //评论数
            $comment1  = $this->db->getOne("select count(1) from  r_news_comment where uid=$reportUid and add_time>=$startTime and add_time<$endTime");//跑步有道帖子回复评论数量
            $comment2  = $this->db->getOne("select count(1) from r_gear_comment where uid=$reportUid and addTime>=$startTime and addTime<$endTime");//装备评论
            $comment3  = $this->db->getOne("select count(1) from  r_activity_comment where uid=$reportUid and add_time>=$startTime and add_time<$endTime");//活动评论
            $comment4  = $this->db->getOne("select count(1) from  r_pm_hall_comment where uid=$reportUid and add_time>=$startTime and add_time<$endTime");//跑么杯大厅评论
          $commentCnt = $comment1+$comment2+$comment3+$comment4;
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-18'.PHP_EOL;

            //群组数
          //$groupIdList = $this->db->getAll("select distinct gid as gid from r_group_add where uid=$reportUid and status=0 and addtime>=$startTime and addtime<$endTime and isShow = 1");
            $groupIdList = $this->db->getAll("select gid from r_gmember where uid = $reportUid and role >=0 && role < 3 and addtime>=$startTime and addtime<$endTime");
            $arrGroup =[];
            $sortG = [];
            if ($groupIdList) {
                foreach ($groupIdList as $kg=>$vg) {
                    $gInfo = $this->load('group')->getGroupInfo($vg['gid']);
                    if (!$gInfo || $gInfo['isDismiss'] == 1) continue;
                    $role = $this->load('group')->getGroupRole($vg['gid'], $reportUid);
                    if ($role == -1) continue;
                    $arrGroup[] = $gInfo;
                    $sortG[] = $gInfo['members'];
                }
            }
           $groupCnt = count($arrGroup);
            $groupCnt > 0 && array_multisort($sortG, SORT_DESC, $arrGroup);
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-19'.PHP_EOL;

            //最活跃群组
          $topGroupId = $arrGroup ? $arrGroup[0]['gid'] : 0;
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-20'.PHP_EOL;

            //参与活动数
            $activityGroup = $this->db->getOne("select count(1) from r_activity_add where uid=$reportUid and add_time >=$startTime and add_time<$endTime");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-20-1'.PHP_EOL;
            $activityMatch = $this->db->getOne("select count(1) from r_match_add where uid=$reportUid and addtime>=$startTime and addtime<$endTime");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-20-2'.PHP_EOL;
            $allXzhangCnt = $this->db->getOne("select count(1) from r_medal_record where uid= $reportUid and medal_id in(1046,1045,1044,1043,1042,1041,1040,1039,1038,1037,1036,1035,1034,1033,1032,1031,1030,1024,1023,1022,1021,1020,1019,1018,1017,1016,1014,1013,1012,1011,1010,1009,1008,1007,1006,1005,1003,1002,1001) and add_time>=$startTime and add_time<$endTime");//所有勋章数
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-21'.PHP_EOL;

            $activityCnt = $activityGroup+$activityMatch+$allXzhangCnt;
            //消耗热量数
           $calorieCnt = $this->db->getOne("select sum(calorie) from r_data where uid=$reportUid and overSpeed = 0
                            and updatetime>=$startTime
                            and updatetime<$endTime");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-22'.PHP_EOL;

            //消耗每公斤脂肪热量
            $fat = $calorieCnt > 0 ? bcdiv($calorieCnt, 7700, 1) : 0;
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-23'.PHP_EOL;

            //跑步总时间 分钟
            $allRunSec = $this->db->getOne("select sum(elapsedtime) from r_data where uid=$reportUid and overSpeed =0 and updatetime>=$startTime
                            and updatetime<$endTime");
            $runMinCnt = $allRunSec > 0 ? round($allRunSec/60) : 0;
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-24'.PHP_EOL;

            //折算微信时间
            $firstTime = $this->db->getOne("select updatetime from r_data where uid=$reportUid and updatetime>=$startTime and updatetime<$endTime order by updatetime asc limit 1");//2016第一条记录产生时间
            $wechatMinCnt = $runMinCnt > 0 ? round($runMinCnt/ceil(($endTime-1-$firstTime)/86400)) : 0;
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-25'.PHP_EOL;

            //用户的勋章数
            $userMedalCnt  = $this->db->getOne("select count(1) from r_medal_record where uid=$reportUid and add_time>=$startTime and add_time<$endTime ");
            //用户获取到的证书数量
            $sql = "select count(*) from r_certificate c left join r_group_activity on r_group_activity.aid = c.aid where c.uid=$reportUid and c.addtime>=$startTime and c.addtime<$endTime and (c.act_type=1 or (c.act_type=0 and (`type`=1 or `type`=2)))";
            $userCertificate = $this->db->getOne($sql);
            //$userCertificate = $this->db->getOne("select count(1) from r_certificate where uid=$reportUid and addtime>=$startTime and addtime<$endTime");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-26'.PHP_EOL;

            //最快配速
            $arrmMaxSpeed = $this->db->getRow("select elapsedtime,mileage,((elapsedtime/mileage)/60) as mispeed from r_data where uid=$reportUid and overSpeed=0 and updatetime>=$startTime and updatetime<$endTime and ((elapsedtime/mileage)/60) >3 order by mispeed asc limit 1");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-27'.PHP_EOL;
            $speed = 0;
            if($arrmMaxSpeed && $maxSpeed = ($arrmMaxSpeed['elapsedtime']/$arrmMaxSpeed['mileage'])/60) {
                $num1 = floor($maxSpeed); //整数部分
                $num2  = $maxSpeed-$num1;
                $speed = bcadd($num1*60,floor($num2*60));//单位 s/km
            }
            //最远距离
            $maxMileage = $this->db->getOne("select max(`mileage`) from r_data where uid=$reportUid and overSpeed = 0 and updatetime>$startTime and updatetime<$endTime");
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-28'.PHP_EOL;

            //跑友数
            //$userFriend = $this->db->getOne("select count(1) from r_friends where uid=$reportUid and status=1 and add_time>=$startTime and add_time<$endTime");
            // 好友列表
            $friendsList = $this->load('friends')->getFriendsList($reportUid);
            $userFriend = count($friendsList);
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-29'.PHP_EOL;

            // 账号等级
            $arrUserInfo = $this->db->getRow("select `level`,addtime from r_user where uid=$reportUid");
            $level = isset($arrUserInfo['level']) ? $arrUserInfo['level'] : 0;
            //使用天数
            if ($arrUserInfo['addtime'] <= $startTime) {
                $useDayCnt = 365;
            } else if($arrUserInfo['addtime'] >= $endTime) {
                $useDayCnt = 0;
            }else {
                $useDayCnt = ceil(bcsub($endTime-1 , $arrUserInfo['addtime'])/86400);
            }
            echo date('Y-m-d H:i:s').'CONTINUE-START-KEY'.$key.'-step-30'.PHP_EOL;

            $data = array(
                'uid'=>$reportUid,
                'mileage'=>$mileage,
                'marathon_cnt'=>$marathonCnt,
                'city_cnt'=>$cityCnt,
                'city'=>$city,
                'run_cnt'=>$runCnt,
                'run_avg_week_cnt'=>$runAvgCnt,
                'often_run_period'=>$oftenRunPeriod,
                'posts_cnt'=>$postsCnt,
                'by_lights'=>$byLightCnt,
                'lights'=>$lightCnt,
                'comment_cnt'=>$commentCnt,
                'group_cnt'=>$groupCnt,
                'most_user_gid'=>$topGroupId,
                'activity_cnt'=>$activityCnt,
                'calorie'=>$calorieCnt,
                'fat_cnt'=>$fat,
                'elapsedtime'=>$runMinCnt,
                'wechat_time'=>$wechatMinCnt,
                'medal_cnt'=>$userMedalCnt,
                'certificate_cnt'=>$userCertificate,
                'max_speed'=>$speed,
                'level'=>$level,
                'run_friends_cnt'=>$userFriend,
                'max_mileage'=>$maxMileage,
                'use_cnt'=>$useDayCnt,
                'date'=>date('Y', $startTime),
                'create_time'=>time()
            );

            $insertStr = common::arrayToString($data);
            $r = $this->db->insert("insert HIGH_PRIORITY into user_run_data_report_year set {$insertStr} on duplicate key update {$insertStr}");
            echo date('Y-m-d H:i:s').'CONTINUE-END-KEY'.$key.PHP_EOL;
        }
        echo date('Y-m-d H:i:s').'OK-END'.PHP_EOL;
    }

    function  doisRedisMem() {
        $value = common::request('val', 'G', 0);
        $type = common::request('ty','G', 0);
        $failDidCnt = $this->redis->sCard(REDIS_PREFIX .'2016YearAnalyzeUserCity');
        if ($type > 1) {
            $a = $this->redis->del(REDIS_PREFIX .'2016YearAnalyzeUserCity');
        } else if ($value > 0) {
            $a = $this->redis->sIsMember(REDIS_PREFIX .'2016YearAnalyzeUserCity', $value);
        } else {
            var_dump($failDidCnt); exit;
        }
        var_dump($a);
    }

    /**
     * 查询用户年度跑过的城市个数
     */
    public function dogetUserRunCityCnt() {
        exit;
        $startTime = strtotime(date('2016-01-01'));
        $endTime = strtotime(date('2017-01-01'));
        $failDidCnt = $this->redis->sCard(REDIS_PREFIX .'2016YearAnalyzeUserCity');
        if ($failDidCnt> 0) {
            echo '$failDidCnt >0'.PHP_EOL;
            $failDid = $this->redis->sMembers(REDIS_PREFIX .'2016YearAnalyzeUserCity');
            $strDid = implode(',', $failDid);
            $arrPoint = $this->db->getAll("select did,uid,point_coordinate from r_data where uid> 0  and overSpeed = 0  and updatetime>=$startTime and updatetime<$endTime
         and  did not in($strDid) and did not in(select did from user_run_city_list) limit 10000");
        } else {
            echo '$failDidCnt =0'.PHP_EOL;
            $arrPoint = $this->db->getAll("select did,uid,point_coordinate from r_data where uid> 0  and overSpeed = 0  and updatetime>=$startTime and updatetime<$endTime
         and  did not in(select did from user_run_city_list) limit 10000");
        }
        if (!$arrPoint) {
            echo '已跑完'.PHP_EOL;
            return false;
        } else {
            echo '未跑完'.count($arrPoint).PHP_EOL;
        }
        foreach ($arrPoint as $key=>$val) {
            if (!$val['point_coordinate']) {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                continue;
            }
            $isDid = $this->db->getOne("select id from user_run_city_list where did={$val['did']}");
            if ($isDid) {
                echo '重复DID'.$val['did'].PHP_EOL;
                continue;
            }

            //第一次打点坐标
            $allPoint = json_decode($val['point_coordinate'] , true);
            if (!$allPoint) {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                continue;
            }
            if (isset($allPoint[0]) && $allPoint[0] != null) {
                $fristPoint = $allPoint[0];
            } else if(isset($allPoint[1]) &&  $allPoint[1] != null) {
                $fristPoint = $allPoint[1];
            } else if(isset($allPoint[2]) &&  $allPoint[2] != null) {
                $fristPoint = $allPoint[2];
            }else if(isset($allPoint[3]) &&  $allPoint[3] != null) {
                $fristPoint = $allPoint[3];
            }else if(isset($allPoint[4]) &&  $allPoint[4] != null) {
                $fristPoint = $allPoint[4];
            }else if(isset($allPoint[5]) &&  $allPoint[5] != null) {
                $fristPoint = $allPoint[5];
            }else if(isset($allPoint[6]) &&  $allPoint[6] != null) {
                $fristPoint = $allPoint[6];
            }else if(isset($allPoint[7]) &&  $allPoint[7] != null) {
                $fristPoint = $allPoint[7];
            }else if(isset($allPoint[8]) &&  $allPoint[8] != null) {
                $fristPoint = $allPoint[8];
            }else if(isset($allPoint[9]) &&  $allPoint[9] != null) {
                $fristPoint = $allPoint[9];
            }else {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                echo '城市查询失败DID-B'.$val['did'].PHP_EOL;
                continue;
            }
            if (isset($fristPoint['lng'])) {
                $lng = $fristPoint['lng'];
                $lat = $fristPoint['lat'];
            } else if(isset($fristPoint['longitude'])) {
                $lng = $fristPoint['longitude'];
                $lat = $fristPoint['latitude'];
            } else {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                echo '城市查询失败DID-A'.$val['did'].PHP_EOL;
                continue;
            }

            //API
            $city = $this->get_city_by_Lng_Lat($lat,$lng);
            if ($city != 10000000 && !$city) {
                echo '城市查询失败DID'.$val['did'].PHP_EOL;
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                continue;
            }
            $year = date('Y',$startTime);
            $time =time();
            $data = array(
                'uid'=>$val['uid'],
                'city'=>$city,
                'date'=>$year,
                'create_time'=>$time,
                'did'=>$val['did']
            );
            $insertStr = common::arrayToString($data);
            $r = $this->db->insert("insert HIGH_PRIORITY into user_run_city_list set {$insertStr} on duplicate key update {$insertStr}");
        }
    }

    function get_city_by_Lng_Lat($lat,$lng){
        $url = "http://api.map.baidu.com/geocoder/v2/?location=$lat,$lng&output=json&coordtype=gcj02ll&ak=x9hasHu3yWStXtGAYAc5HEhMZ0CvcLmd";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        $output = curl_exec($ch);
        curl_close($ch);
        $reslt = json_decode($output,true);
        if (!$reslt || $reslt['status'] <> 0) {
            echo '失败状态码:'.$reslt['status'].PHP_EOL;
            return 10000000 ;
        }
        $addressComponent = $reslt['result']['addressComponent'];
        $city = $addressComponent['city'];
        return $city;
    }

    /**
     * 2016年用户跑步年终数据接口
     */
    public function dogetYearRunDataReviewForUser() {
        $uid = $this->uid;
        $reportUid = (int)common::request('uid', 'G', 0);
        if (!$reportUid) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $reportUid,'header');
        $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $reportUid,'nickname');
        $result = array(
            'uid'=>$reportUid,
            'nickname'=>$nickname,
            'header'=>$header,
            'mileage'=>0,
            'marathonCnt'=>0,
            'cityCnt'=>0,
            'city'=>'',
            'runTimeMsg'=>'',
            'runCnt'=>0,
            'runAvgWeekCnt'=>0,
            'postsCnt'=>0,
            'byLights'=>0,
            'lights'=>0,
            'commentCnt'=>0,
            'groupCnt'=>0,
            'mostUserGroup'=>'',
            'activityCnt'=>0,
            'calorie'=>0,
            'fatCnt'=>0,
            'elapsedtime'=>0,
            'wechatTime'=>0,
            'medalCnt'=>0,
            'certificateCnt'=>0,
            'maxSpeed'=>0,
            'level'=>'',
            'runFriendsCnt'=>0,
            'maxMileage'=>0,
            'useCnt'=>0,
            'targetMileageType'=>0,
            'lightMileage'=>0
        );

        $startTime = strtotime(date('2016-01-01'));
        $endTime = strtotime(date('2017-01-01'));
        $date = date('Y', $startTime);
        $info = $this->db->getRow("select * from user_run_data_report_year where uid=$reportUid and `date`='$date' limit 1");
        if ($info) {
            $levelInfo = $info['level'] > 0 ? common::$runLevel[$info['level']] : '';
            //最活跃群组名称
            $mostUserGName = $info['most_user_gid'] > 0 ? $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$info['most_user_gid'],'name') : '';
            //经常跑步时间段
            $oftenRunTimeArr = array(1=>'早晨',2=>'上午', 3=>'中午', 4=>'下午', 5=>'夜晚');
            $oftenRunTimeMsg = isset($oftenRunTimeArr[$info['often_run_period']]) ? $oftenRunTimeArr[$info['often_run_period']] : '';
            $result = array(
                'uid'=>$reportUid,
                'nickname'=>$nickname,
                'header'=>$header,
                'mileage'=>$info['mileage'],
                'marathonCnt'=>$info['marathon_cnt'],
                'cityCnt'=>$info['city_cnt'],
                'city'=>$info['city'],
                'runTimeMsg'=>$oftenRunTimeMsg,
                'runCnt'=>$info['run_cnt'],
                'runAvgWeekCnt'=>$info['run_avg_week_cnt'],
                'postsCnt'=>$info['posts_cnt'],
                'byLights'=>$info['by_lights'],
                'lights'=>$info['lights'],
                'commentCnt'=>$info['comment_cnt'],
                'groupCnt'=>$info['group_cnt'],
                'mostUserGroup'=>$mostUserGName,
                'activityCnt'=>$info['activity_cnt'],
                'calorie'=>$info['calorie'],
                'fatCnt'=>$info['fat_cnt'],
                'elapsedtime'=>$info['elapsedtime'],
                'wechatTime'=>$info['wechat_time'],
                'medalCnt'=>$info['medal_cnt'],
                'certificateCnt'=>$info['certificate_cnt'],
                'maxSpeed'=>$info['max_speed'] > 0 ? common::sec3format($info['max_speed']) : '',
                'level'=>$levelInfo ? $levelInfo['title'] : '',
                'runFriendsCnt'=>$info['run_friends_cnt'],
                'maxMileage'=>$info['max_mileage'],
                'useCnt'=>$info['use_cnt'],
                'targetMileageType'=>$info['target_mileage_type'],
                'lightMileage'=>$info['light_mileage']
            );
        }
        $this->result['result']['list'] = $result;


    }

    /**
     * 2016年用户跑步数据增加年终点赞接口
     * 单个人可以重复点赞
     */
    public function doincTargetMileageByLight() {
        $uid = $this->uid;
        $reportUid = (int)common::request('uid', 'P', 0, true);
        if (!$reportUid) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $isUser = $this->db->getOne("select uid from r_user where uid=$reportUid");
        if (!$isUser) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $startTime = strtotime(date('2016-01-01'));
        $endTime = strtotime(date('2017-01-01'));
        $sql = "select light_mileage from user_run_data_report_year where uid=$reportUid and `date`=".date('Y', $startTime);
        $lightMileage = $this->db->getOne("$sql");
        if ($lightMileage >=9999) {
            $this->result['result']['is_success'] = 1;
            exit;
        }
        $insertStr = "uid=$reportUid,light_mileage=light_mileage+1,date=".date('Y', $startTime);
        $result = $this->db->insert("insert HIGH_PRIORITY into user_run_data_report_year set {$insertStr} on duplicate key update {$insertStr}");
        $this->result['result']['is_success'] = 0;
        if ($result) {
            $this->result['result']['is_success'] = 1;
        }
    }

    /**
     * 2016年用户跑步数据设置目标里程类型
     * 设置用户目标公里数类型
     */
    public function dosetUserTargetType() {
        $uid = $this->uid;
        if (!$uid) {
            $_ENV['error']->getErrors(201);
            exit;
        }
        $targetMileageType = (int)common::request('targetMileageType', 'P', 0, true);
        if (!in_array($targetMileageType, array(1,2,3,4))) {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $startTime = strtotime(date('2016-01-01'));
        $endTime = strtotime(date('2017-01-01'));
        $insertStr = "uid=$uid,target_mileage_type=$targetMileageType,date=".date('Y', $startTime);
        $result = $this->db->insert("insert HIGH_PRIORITY into user_run_data_report_year set {$insertStr} on duplicate key update {$insertStr}");
        $this->result['result']['is_success'] = 0;
        if ($result !== false) {
            $this->result['result']['is_success'] = 1;
        }
    }

    public function dogetTowerOther() {
        exit;
        $idKey = REDIS_PREFIX .'2016YearAnalyzeUserCityFiveId';
        $usrtCntKey = REDIS_PREFIX .'2016YearAnalyzeUserCityCount';
//        $failDidCnt = $this->redis->del($idKey);exit;
        $id = 0;
        $count = $this->redis->zSize($usrtCntKey);
        if ($count) {
            $lastUidKey = $this->redis->zRevRange($usrtCntKey, 0, -1);
            if ($lastUidKey) {
                $idArr = $this->redis->zRevRange($usrtCntKey, 0, -1, true);
                $id = ($idArr && isset($idArr[$lastUidKey[0]])) ? $idArr[$lastUidKey[0]]: 0;
            }
        }
        echo date('Y-m-d H:i:s').'ID：'.$id;
        $list = $this->db->getAll("select id,uid from user_run_city_list where id>$id limit 10000");
        if (!$list) {
            echo date('Y-m-d H:i:s').'跑完咯';exit;
        }
        foreach ($list as $key=>$val) {
            $lastUidKey = $this->redis->zRevRange($usrtCntKey, 0, -1);
            if ($lastUidKey && in_array($val['uid'] , $lastUidKey)) {
                continue;
            }
            $this->redis->zAdd($usrtCntKey, $val['id'], $val['uid']);
            $phone = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'], 'phone');
            if (!$phone) {
               continue;
            }
            $cnt = $this->db->getOne("select count(1) from user_run_city_list where uid={$val['uid']}");
            if ($cnt >= 5) {
                $this->redis->zAdd($idKey, $val['id'], $val['uid']);
            }
        }
    }

    /**
     * 给用户发短信
     */
    public function dogetValidUser() {
        echo date("Y-m-d H:i:s").' START'.PHP_EOL;
        ini_set('memory_limit','2048M');
        $sql = "SELECT distinct a.uid FROM `r_user` a left join r_data b ON a.uid=b.uid where a.total_rate>=5 and a.phone<>0 and b.uid>0 and a.uid not in(SELECT distinct a.uid FROM `r_user` a left join r_data b ON a.uid=b.uid where b.uid>0 and b.updatetime>=1475251200)";
        $list = $this->db->getAll($sql);
        echo date("Y-m-d H:i:s").' CONTINUE-1'.PHP_EOL;
        if ($list) {
            foreach ($list as $key=>$val) {
                $data = array('uid'=>$val['uid'],'flag'=>0);
                $insertStr = common::arrayToString($data);
                echo date("Y-m-d H:i:s").' START-KEY'.$key.'-step-1'.PHP_EOL;
                $r = $this->db->insert("insert HIGH_PRIORITY into user_run_year_smg set {$insertStr} on duplicate key update {$insertStr}");
                echo date("Y-m-d H:i:s").' START-KEY'.$key.'-step-2'.PHP_EOL;
            }
        }
        echo date("Y-m-d H:i:s").' END'.PHP_EOL;

    }

    /**
     * 发短信
     */
    public function dosendValidMsg(){
        $count = $this->db->getOne("select count(1) from user_run_year_smg where flag=1");
        $limit = 20000-$count;
        if ($limit <=0) {
            echo date("Y-m-d H:i:s").' 已发送完成-A'.PHP_EOL;exit;
        }
        $list= $this->db->getAll("select * from user_run_year_smg where flag=0 limit $limit");
        if (!$list) {
            echo date("Y-m-d H:i:s").' 已发送完成-B'.PHP_EOL;exit;
        }
        include FILE.'lib/sms.class.php';
        foreach ($list as $key=>$val) {
            $sms = new sms();
            echo date("Y-m-d H:i:s").' START-KEY'.$key.'-step-1'.PHP_EOL;
            $phone = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'], 'phone');
            if (!$phone) continue;
            $alphaId = $this->alphaId->getHash($val['uid']);
            $resultCode =  $sms->testinSMSNewYear($phone, $alphaId);
            echo date("Y-m-d H:i:s").' START-KEY'.$key.'-step-2'.PHP_EOL;
            if($resultCode == 1000) { //写入表记录
                echo date("Y-m-d H:i:s").' START-KEY'.$key.'-发送成功-step-3'.PHP_EOL;
                $data = array('uid'=>$val['uid'],'flag'=>1);
                $insertStr = common::arrayToString($data);
                $r = $this->db->insert("insert HIGH_PRIORITY into user_run_year_smg set {$insertStr} on duplicate key update {$insertStr}");
            } else {
                echo date("Y-m-d H:i:s").' START-KEY'.$key.'-发送失败-step-4,状态码:'.var_export($resultCode, true).PHP_EOL;
            }
        }
        echo date("Y-m-d H:i:s").' 已发送完成-C'.PHP_EOL;
    }

    public function dogetSome() {
        $id = (int)common::request('uid','G', 0);
        $all = $this->db->getAll("select * from user_run_data_report_year where uid=$id");
        print_r($all);
    }
}

